import os
import threading
from queue import Queue
import pytesseract
import json
import time
from finder import Finder
from finderFactory import FinderFactory
import tools

search_word = "国家"
lock = threading.Lock()


def process_pdf(filename):
    print(f"------Processing file: {filename}")
    print(f"------当前线程是: {threading.current_thread().name}")
    if "MACOS" in filename:
        return
    if "~" in filename:
        return
    if "$" in filename:
        return

    a_finder = FinderFactory.create_finder_with_file_path(filename)
    a_finder.search_file(filename, search_word)


# 遍历目录并将文件名放入队列中
def enqueue_files(directory, queue):
    for root, dirs, files in os.walk(directory):
        for fileName in files:
            # if fileName.lower().endswith('.pdf'):
            file_path = os.path.join(root, fileName)
            print(f'put file:${file_path}')
            queue.put(file_path)


def worker(queue):
    while not queue.empty():
        filename = queue.get()
        process_pdf(filename)
        queue.task_done()


def main(directory):
    print("------------开始处理------------------")
    # 创建一个队列来存储文件名
    file_queue = Queue()

    # 创建线程来遍历目录并将文件名放入队列
    enqueue_thread = threading.Thread(target=enqueue_files, args=(directory, file_queue))
    enqueue_thread.start()

    time.sleep(5)

    # 创建工作线程池
    num_threads = 10  # 例如，使用4个线程
    threads = []
    for _ in range(num_threads):
        t = threading.Thread(target=worker, args=(file_queue,))
        t.start()
        threads.append(t)

        # 等待队列中的所有任务都处理完毕
    file_queue.join()

    # 等待所有工作线程完成
    for t in threads:
        t.join()

    with open(get_cache_file_path(), "w", encoding="utf-8") as f:
        json.dump(tools.global_store, f, ensure_ascii=False, indent=4)

    print("------------------------------")
    print("All files have been processed.")


def get_cache_file_path():
    return f'{directory_path}/all_pdf_info.json'


def search_from_global_store():
    for file_info, text_value in tools.global_store.items():
        if search_word.lower() in Finder.process_text_if_need(text_value.lower()):
            if '废止' not in file_info and '废弃' not in file_info:
                print(f"Found '{search_word}' in {file_info}")


# directory_path = "D:/工作资料/03_规章制度/"
# directory_path = f'{os.getcwd()}\\测试目录\\'
# directory_path = "../测试目录/"
directory_path = "D:/工作资料/01贸易领域审计/02过程表/04可行性评估/002-系统调研/0003-系统资料/01-工程系统调研资料"
# 使用示例
if __name__ == "__main__":
    # pytesseract.pytesseract.tesseract_cmd = r'E:\D其他软件\提效工具\tesseract-ocr\tesseract.exe'
    pytesseract.pytesseract.tesseract_cmd = r'D:\IDES\tesseract_ocr\tesseract.exe'

    while True:
        search_word = input("请输入你要查找的内容，然后点击回车^_^\n")
        if len(tools.global_store) != 0:
            search_from_global_store()
        else:
            if os.path.exists(get_cache_file_path()):
                with open(get_cache_file_path(), 'r', encoding='utf-8') as file:
                    tools.global_store = json.load(file)
                if len(tools.global_store) != 0:
                    search_from_global_store()
            else:
                main(directory_path)
